package com.etcbase.dcs.utils.gui;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;

public class LayoutWidthAnimator {

	private int durationTime;
	private ViewGroup viewGroupLayout;
	private AnimatorListener userAnimatorListener;
	private int startWidth;
	private int stopWidth;
	private int widthDifference;

	public LayoutWidthAnimator(ViewGroup layout, int durationTime) {
		viewGroupLayout = layout;
		this.durationTime = durationTime;
	}



	// start animating to the given target width
	public void start(int stopWidth, AnimatorListener userAnimatorListener) {
		this.userAnimatorListener = userAnimatorListener;
		startWidth = viewGroupLayout.getWidth();
		this.stopWidth = stopWidth;
		widthDifference = stopWidth - startWidth;

		ValueAnimator animator = new ValueAnimator();
		animator.setDuration(durationTime);
		animator.setIntValues(new int[] { 0, 0 }); // the values are irrelevant
		animator.addUpdateListener(userAimatorUpdateListener);
		animator.addListener(animatorListener);
		animator.start();
	}

	private void setLayoutWidth(int width) {
		LayoutParams params = viewGroupLayout.getLayoutParams();
		params.width = width;
		viewGroupLayout.setLayoutParams(params);
	}

	private AnimatorUpdateListener userAimatorUpdateListener = new AnimatorUpdateListener() {
		@Override
		public void onAnimationUpdate(ValueAnimator animation) {
			setLayoutWidth((int) (startWidth + widthDifference
					* animation.getCurrentPlayTime() / durationTime));
		}
	};

	private AnimatorListener animatorListener = new AnimatorListener() {
		@Override
		public void onAnimationStart(Animator animation) {
			if (userAnimatorListener != null)
				userAnimatorListener.onAnimationStart(animation);
		}

		@Override
		public void onAnimationRepeat(Animator animator) {
			if (userAnimatorListener != null)
				userAnimatorListener.onAnimationRepeat(animator);
		}

		@Override
		public void onAnimationEnd(Animator animator) {
			// set final values for the dimensions of the layout
			setLayoutWidth(stopWidth);

			// then call the users listener
			if (userAnimatorListener != null)
				userAnimatorListener.onAnimationEnd(animator);
		}

		@Override
		public void onAnimationCancel(Animator animator) {
			if (userAnimatorListener != null)
				userAnimatorListener.onAnimationCancel(animator);
		}
	};
}